package com.ck.common.service.impl;

import com.ck.common.service.OperationLogService;
import com.ck.common.service.UserService;
import com.ck.constant.*;
import com.ck.dao.UserMapper;
import com.ck.exception.ServiceException;
import com.ck.model.common.OperationLog;
import com.ck.model.common.User;
import com.ck.model.common.dto.UserListDTO;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.vo.UserListVO;
import com.ck.model.common.vo.UserRoleSelectListVO;
import com.ck.util.HttpUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.List;

/**
 * 用户Service实现类
 *
 * @author dxy
 * @date 2018/6/21 15:27
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OperationLogService operationLogService;

	/**
	 * 保存用户
	 *
	 * @param user    User
	 * @param roleIds 角色IDS
	 * @param request HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void insertUser(User user, String roleIds, HttpServletRequest request) throws ServiceException {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		if (StringUtils.isBlank(user.getCompanyCode())) {
			user.setCompanyCode(companyCode);
		}
		//MD5加密密码
		String password = user.getPassword();
		if (StringUtils.isBlank(password)) {
			throw new ServiceException("密码不能为空");
		}
		String md5Password = DigestUtils.md5Hex(password);
		user.setPassword(md5Password);
		//用户类型
		Integer loginUserType = loginUser.getType();
		if (user.getType() == null) {
			user.setType(loginUserType);
		}
		user.setAddTime(System.currentTimeMillis());
		user.setStatus(BusinessConstant.STATUS_ENABLE);
		if(user.getSuperAdminUser() == null){
			user.setSuperAdminUser(BusinessConstant.SUPER_ADMIN_USER_NO);
		}
		//保存用户
		userMapper.insertUser(user);
		Long userId = user.getUserId();
		if (userId == null) {
			throw new ServiceException("保存用户失败");
		}
		//保存用户角色关系
		if (StringUtils.isNotBlank(roleIds)) {
			userMapper.insertUserRole(userId, roleIds.split(","));
		}
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		operationLog.setCopmanyCode(companyCode);
		operationLog.setOperationContent("保存用戶,用戶ID为:" + userId);
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_USER);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 修改用户
	 *
	 * @param user    User
	 * @param roleIds 角色IDS
	 * @param request HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateUser(User user, String roleIds, HttpServletRequest request) {
		//MD5加密密码
		String password = user.getPassword();
		if (StringUtils.isNotBlank(password)) {
			String md5Password = DigestUtils.md5Hex(password);
			user.setPassword(md5Password);
		}
		user.setUpdateTime(System.currentTimeMillis());
		//更新用户
		userMapper.updateUserById(user);

		Long userId = user.getUserId();
		if (StringUtils.isNotBlank(roleIds)) {
			//删除用户角色关系
			userMapper.deleteUserRoleByUserId(userId);
			//保存用户角色关系
			userMapper.insertUserRole(userId, roleIds.split(","));
		}
		//记录操作日志
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		OperationLog operationLog = new OperationLog();
		operationLog.setCopmanyCode(loginUser.getCompanyCode());
		operationLog.setOperationContent("修改用戶,用戶ID为:" + userId);
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_USER);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 通过用户名获取用户
	 *
	 * @param userName 用户名
	 * @return User(用户)
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public User getUserByUserName(String userName) {
		return userMapper.getUserByUserName(userName);
	}

	/**
	 * 获取用戶列表
	 *
	 * @param companyCode 商家编码
	 * @param status      状态
	 * @param userName    用户名
	 * @param pageNum     当前页
	 * @param pageSize    条数
	 * @return PageInfo<UserListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public PageInfo<UserListVO> listUser(String companyCode, Integer status, String userName, Integer pageNum, Integer pageSize) throws ServerException {
		if (StringUtils.isBlank(companyCode)) {
			throw new ServerException("公司编码不能为空");
		}
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<UserListDTO> page = userMapper.listUser(companyCode, status, userName);
		//把Page转化为PageInfo
		PageInfo<UserListVO> pageInfo = new PageInfo<>();
		pageInfo.setPageNum(pageNum);
		pageInfo.setPageSize(pageSize);
		pageInfo.setTotal(page.getTotal());
		List<UserListVO> voList = Lists.newArrayList();
		StringBuilder roleNameSb = new StringBuilder();
		StringBuilder roleIdSb = new StringBuilder();
		for (UserListDTO dto : page.getResult()) {
			UserListVO vo = new UserListVO();
			Long userId = dto.getUserId();
			vo.setUserId(userId);
			vo.setDepartmentName(dto.getDepartmentName());
			vo.setUserName(dto.getUserName());
			vo.setRealname(dto.getRealname());
			vo.setMobilePhone(dto.getMobilePhone());
			vo.setStatus(dto.getStatus());
			vo.setSuperAdminUser(dto.getSuperAdminUser());
			//所属角色
			List<UserRoleSelectListVO> userRoleList = userMapper.listUserRoleName(userId);
			if (CollectionUtils.isNotEmpty(userRoleList)) {
				for (int i = 0; i < userRoleList.size(); i++) {
					UserRoleSelectListVO userRoleSelectVO = userRoleList.get(i);
					if (i > 0) {
						roleNameSb.append(",");
					}
					roleNameSb.append(userRoleSelectVO.getRoleName());
					if (i > 0) {
						roleIdSb.append(",");
					}
					roleIdSb.append(userRoleSelectVO.getRoleId());
				}
				vo.setBelongRole(roleNameSb.toString());
				vo.setBelongRoleIds(roleIdSb.toString());
				roleNameSb.setLength(0);
				roleIdSb.setLength(0);
			} else {
				vo.setBelongRole("");
				vo.setBelongRoleIds("");
			}
			voList.add(vo);
		}
		pageInfo.setList(voList);
		return pageInfo;
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public User getUserById(Long userId) {
		return userMapper.getUserById(userId);
	}

	/**
	 * 根据主键更新
	 * @param user
	 */
	@Override
	public void updateByPrimaryKey(User user) {
		userMapper.updateUserById(user);
	}

	/**
	 * 重置密码
	 * @param userId 用户ID
	 * @param password 密码
	 * @param loginUser 当前登录用户
	 * @param remortIP 远程IP
	 * @throws ServiceException
	 */
	@Override
	public void resetPassword(Long userId, String password, User loginUser, String remortIP) throws ServiceException {
		if (userId == null || StringUtils.isBlank(password)
				|| loginUser == null || StringUtils.isBlank(remortIP)) {
			throw new ServiceException("输入参数不能为空");
		}
		//查询用户
		User user = userMapper.getUserById(userId);
		if (user == null) {
			throw new ServiceException("被重置密码的用户不存在，请联系管理员");
		}
		//重置密码
		userMapper.resetPassword(userId, DigestUtils.md5Hex(password));
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		operationLog.setCopmanyCode(loginUser.getCompanyCode());
		operationLog.setOperationContent("重置用户" + user.getUserName() + "的密码");
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_USER);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(remortIP);
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 修改密码
	 *
	 * @param passwordUser 待修改密码的用户对象
	 * @param loginUser    当前系统登录的用户
	 * @param ip           登录用户ID
	 * @return 影响行数
	 */
	@Override
	public void updatePassword(User passwordUser, User loginUser, String ip) {
		//MD5加密密码
		String password = passwordUser.getPassword();
		if (StringUtils.isNotBlank(password)) {
			String md5Password = DigestUtils.md5Hex(password);
			passwordUser.setPassword(md5Password);
		}
		passwordUser.setUpdateTime(System.currentTimeMillis());
		//更新用户
		userMapper.updateUserById(passwordUser);
		operationLogService.saveSuccessOperationLog("修改密码，用户ID为:" + loginUser.getUserId(),
				ModuleConstant.MODULE_SYSTEM + "-" + ModuleConstant.MODULE_SYS_LOG, loginUser, ip);
	}

    /**
     * 启用禁用用户
     *
     * @param user      待操作的用户
     * @param loginUser 登录的用户
     * @param remortIP  登录用户ip
     * @author linqiang
     */
    @Override
    public void enableDisableUser(User user, User loginUser, String remortIP) {
        String msg = "%s，用户ID为:%s";
        if (OperationType.DISABLE_USER.getValue().equals(user.getStatus())) {
            //禁用
            msg = String.format(msg, OperationType.DISABLE_USER.getName(), user.getUserId());
        } else if (OperationType.ENABLE_USER.getValue().equals(user.getStatus())) {
            //启用
            msg = String.format(msg, OperationType.ENABLE_USER.getName(), user.getUserId());
        }
        user.setUpdateTime(System.currentTimeMillis());
        userMapper.updateUserById(user);
        operationLogService.saveSuccessOperationLog(msg,
                (ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_USER), loginUser, remortIP);
    }
}
